import { createFileRoute } from '@tanstack/react-router'
import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { StorageService, generateId } from '../services/storage'
import { LetterForm } from '../components/LetterForm'
import { StickyNoteForm } from '../components/StickyNoteForm'

interface Letter {
  id: number
  title: string
  date: string
  author: string
  content: string
  isHandwritten: boolean
}

interface StickyNote {
  id: number
  content: string
  author: string
  color: string
  rotation: number
}

function LoveLetters() {
  const [letters, setLetters] = useState<Letter[]>([])
  const [stickyNotes, setStickyNotes] = useState<StickyNote[]>([])
  const [showLetterForm, setShowLetterForm] = useState(false)
  const [showNoteForm, setShowNoteForm] = useState(false)
  const [editingLetter, setEditingLetter] = useState<Letter | null>(null)

  // 加载数据
  useEffect(() => {
    const savedLetters = StorageService.getLoveLetters()
    const savedNotes = StorageService.getStickyNotes()
    
    if (savedLetters.length > 0) {
      setLetters(savedLetters)
    } else {
      const defaultLetters: Letter[] = [
        {
          id: 1,
          title: "第一封情书",
          date: "2024.02.14",
          author: "他",
          content: "亲爱的，从遇见你的那一刻起，我的世界就变得不一样了...\n\n每天醒来第一个想到的是你，睡前最后一个念头也是你。你就像阳光一样照亮了我的生活，让我的每一天都充满了意义。\n\n我想和你一起走过春夏秋冬，看遍世间美景，体验人生的酸甜苦辣。因为有了你，一切都变得美好起来。\n\n永远爱你的，\n他 💕",
          isHandwritten: true
        },
        {
          id: 2,
          title: "回信",
          date: "2024.02.15",
          author: "她",
          content: "看到你的信，我的心跳得好快，原来这就是心动的感觉...\n\n你知道吗？当我读完你的信时，眼泪不自觉地流了下来。不是因为难过，而是因为太幸福了。\n\n从来没有人对我说过这样的话，从来没有人让我感受到如此深沉的爱意。你让我相信，这个世界上真的有童话般的爱情。\n\n我也想对你说，我爱你，比昨天多一点，比明天少一点。\n\n永远属于你的，\n她 💖",
          isHandwritten: false
        }
      ]
      setLetters(defaultLetters)
      StorageService.saveLoveLetters(defaultLetters)
    }
    
    if (savedNotes.length > 0) {
      setStickyNotes(savedNotes)
    } else {
      const defaultNotes: StickyNote[] = [
        { id: 1, content: "记得吃早餐哦 💕", author: "她", color: "bg-yellow-200", rotation: 1 },
        { id: 2, content: "想你了 🥰", author: "他", color: "bg-pink-200", rotation: -2 },
        { id: 3, content: "今天的月亮很美", author: "她", color: "bg-blue-200", rotation: 2 },
        { id: 4, content: "爱你 ❤️", author: "他", color: "bg-green-200", rotation: -1 },
        { id: 5, content: "一起看星星吧 ✨", author: "她", color: "bg-purple-200", rotation: 3 }
      ]
      setStickyNotes(defaultNotes)
      StorageService.saveStickyNotes(defaultNotes)
    }
  }, [])

  // 保存数据
  const saveLetters = (newLetters: Letter[]) => {
    setLetters(newLetters)
    StorageService.saveLoveLetters(newLetters)
  }

  const saveNotes = (newNotes: StickyNote[]) => {
    setStickyNotes(newNotes)
    StorageService.saveStickyNotes(newNotes)
  }

  // 添加新情书
  const handleAddLetter = (letterData: Omit<Letter, 'id'>) => {
    const newLetter: Letter = {
      ...letterData,
      id: parseInt(generateId())
    }
    const updatedLetters = [newLetter, ...letters]
    setLetters(updatedLetters)
    StorageService.saveLoveLetters(updatedLetters)
    setShowLetterForm(false)
  }

  const handleUpdateLetter = (updatedLetter: Letter) => {
    const updatedLetters = letters.map(letter => 
      letter.id === updatedLetter.id ? updatedLetter : letter
    )
    setLetters(updatedLetters)
    StorageService.saveLoveLetters(updatedLetters)
    setEditingLetter(null)
    setShowLetterForm(false)
  }

  // 删除情书
  const deleteLetter = (id: number) => {
    if (confirm('确定要删除这封情书吗？')) {
      const updatedLetters = letters.filter(letter => letter.id !== id)
      saveLetters(updatedLetters)
      if (selectedLetter?.id === id) {
        setSelectedLetter(null)
      }
    }
  }

  // 添加便签
  const addStickyNote = (noteData: Omit<StickyNote, 'id' | 'rotation'>) => {
    const colors = ['bg-yellow-200', 'bg-pink-200', 'bg-blue-200', 'bg-green-200', 'bg-purple-200', 'bg-orange-200']
    const newNote: StickyNote = {
      ...noteData,
      id: parseInt(generateId(), 36),
      color: colors[Math.floor(Math.random() * colors.length)],
      rotation: Math.floor(Math.random() * 7) - 3 // -3 to 3 degrees
    }
    const updatedNotes = [...stickyNotes, newNote]
    saveNotes(updatedNotes)
    setShowNoteForm(false)
  }

  // 删除便签
  const deleteStickyNote = (id: number) => {
    const updatedNotes = stickyNotes.filter(note => note.id !== id)
    saveNotes(updatedNotes)
  }

  const [selectedLetter, setSelectedLetter] = useState<Letter | null>(null)


  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-pink-50">
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-4xl font-bold text-center text-gray-800 mb-8 font-serif">
          情书便签墙 💌
        </h1>
        
        <div className="max-w-6xl mx-auto">
          <div className="grid md:grid-cols-3 gap-6">
            {/* 情书列表 */}
            <div className="md:col-span-1 space-y-4">
              <h2 className="text-2xl font-semibold text-rose-600 mb-4 flex items-center">
                <span className="mr-3">📝</span>
                我们的情书
              </h2>
              
              {letters.map(letter => (
                <motion.div
                  key={letter.id}
                  onClick={() => setSelectedLetter(letter)}
                  className={`bg-white/80 backdrop-blur-sm rounded-xl p-4 shadow-lg cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-105 ${
                    selectedLetter?.id === letter.id ? 'ring-2 ring-rose-400' : ''
                  }`}
                  whileHover={{ y: -2 }}
                  layout
                >
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="font-medium text-gray-700">{letter.title}</h3>
                    <div className="flex items-center space-x-2">
                      {letter.isHandwritten && (
                        <span className="text-xs bg-rose-100 text-rose-600 px-2 py-1 rounded-full">
                          手写
                        </span>
                      )}
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          setEditingLetter(letter)
                        }}
                        className="text-blue-500 hover:text-blue-700 text-xs"
                      >
                        ✏️
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          deleteLetter(letter.id)
                        }}
                        className="text-red-500 hover:text-red-700 text-xs"
                      >
                        🗑️
                      </button>
                    </div>
                  </div>
                  <p className="text-sm text-gray-500 mb-2">{letter.date} · {letter.author}</p>
                  <p className="text-sm text-gray-600 line-clamp-2">
                    {letter.content.split('\n')[0]}
                  </p>
                </motion.div>
              ))}
              
              {/* 添加新情书按钮 */}
              <motion.button 
                onClick={() => setShowLetterForm(true)}
                className="w-full bg-gradient-to-r from-rose-400 to-pink-400 text-white rounded-xl p-4 hover:from-rose-500 hover:to-pink-500 transition-all duration-300 shadow-lg"
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <span className="text-2xl mb-2 block">✍️</span>
                写一封新情书
              </motion.button>
            </div>

            {/* 情书详情 */}
            <div className="md:col-span-2">
              {selectedLetter ? (
                <div className="bg-white/90 backdrop-blur-sm rounded-2xl p-8 shadow-xl">
                  <div className="mb-6">
                    <h2 className="text-3xl font-serif text-gray-800 mb-2">
                      {selectedLetter.title}
                    </h2>
                    <div className="flex items-center space-x-4 text-gray-500">
                      <span>{selectedLetter.date}</span>
                      <span>·</span>
                      <span>来自 {selectedLetter.author}</span>
                      {selectedLetter.isHandwritten && (
                        <>
                          <span>·</span>
                          <span className="text-rose-500">手写原稿</span>
                        </>
                      )}
                    </div>
                  </div>
                  
                  <div className="prose prose-lg max-w-none">
                    <div className={`${selectedLetter.isHandwritten ? 'font-handwriting' : 'font-serif'} text-gray-700 leading-relaxed whitespace-pre-line`}>
                      {selectedLetter.content}
                    </div>
                  </div>
                  
                  {selectedLetter.isHandwritten && (
                    <div className="mt-8 p-4 bg-rose-50 rounded-xl">
                      <p className="text-rose-600 text-sm flex items-center">
                        <span className="mr-2">📷</span>
                        这是手写原稿的电子版，点击查看原始照片
                      </p>
                    </div>
                  )}
                  
                  <div className="mt-8 flex justify-center">
                    <div className="flex space-x-4">
                      <button className="px-6 py-2 bg-rose-100 text-rose-600 rounded-lg hover:bg-rose-200 transition-colors">
                        ❤️ 收藏
                      </button>
                      <button className="px-6 py-2 bg-pink-100 text-pink-600 rounded-lg hover:bg-pink-200 transition-colors">
                        💬 回复
                      </button>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-12 shadow-lg text-center">
                  <div className="text-6xl mb-4">💌</div>
                  <h3 className="text-2xl font-serif text-gray-600 mb-2">
                    选择一封情书来阅读
                  </h3>
                  <p className="text-gray-500">
                    每一封信都承载着我们的爱意与思念
                  </p>
                </div>
              )}
            </div>
          </div>
          
          {/* 便签墙 */}
          <div className="mt-12">
            <h2 className="text-2xl font-semibold text-pink-600 mb-6 flex items-center">
              <span className="mr-3">📋</span>
              爱的便签墙
            </h2>
            
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
              <AnimatePresence>
                {stickyNotes.map(note => (
                  <motion.div
                    key={note.id}
                    className={`${note.color} p-4 rounded-lg shadow-md cursor-pointer group relative`}
                    style={{ transform: `rotate(${note.rotation}deg)` }}
                    whileHover={{ rotate: 0, scale: 1.05 }}
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.8 }}
                    layout
                  >
                    <button
                      onClick={() => deleteStickyNote(note.id)}
                      className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      ×
                    </button>
                    <p className="text-sm text-gray-700 font-handwriting">
                      "{note.content}"
                    </p>
                    <p className="text-xs text-gray-500 mt-2">- {note.author}</p>
                  </motion.div>
                ))}
              </AnimatePresence>
              
              {/* 添加便签 */}
              <motion.div 
                onClick={() => setShowNoteForm(true)}
                className="bg-gray-100 border-2 border-dashed border-gray-300 p-4 rounded-lg flex items-center justify-center cursor-pointer hover:bg-gray-200 transition-colors"
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                <div className="text-center text-gray-500">
                  <div className="text-2xl mb-1">+</div>
                  <p className="text-xs">添加便签</p>
                </div>
              </motion.div>
            </div>
          </div>
        </div>

        {/* 情书表单 */}
        <LetterForm
          isOpen={showLetterForm}
          onClose={() => {
            setShowLetterForm(false)
            setEditingLetter(null)
          }}
          onSubmit={(letterData) => {
            if (editingLetter) {
              handleUpdateLetter({ ...letterData, id: editingLetter.id })
            } else {
              handleAddLetter(letterData)
            }
          }}
          initialData={editingLetter || undefined}
        />

        {/* 便签表单 */}
        <StickyNoteForm 
          isOpen={showNoteForm}
          onClose={() => setShowNoteForm(false)}
          onSubmit={addStickyNote}
        />
      </div>
    </div>
  )
}

export const Route = createFileRoute('/love-letters')({
  component: LoveLetters,
})
